package com.yuneec.fly.utils;

import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

import java.util.List;

public class WifiHelper {

    private static WifiConfiguration CreateWifiInfo(String SSID, String Password, int type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = SSID;
        // nopass
        if (type == WifiCipherType.WIFICIPHER_NOPASS) {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // wep
        if (type == WifiCipherType.WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // wpa
        if (type == WifiCipherType.WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            return null;
        }
        return config;
    }

    //提供一个外部接口，传入要连接的无线网
    public static boolean connectWifi(WifiManager wifiManager, String SSID, String password, int type) {
        if (!SSID.startsWith("\"") && !SSID.endsWith("\"")) {
            SSID = "\"" + SSID + "\"";
        }
        LogUtils.e("connect to wifi " + SSID + " , password : " + password + " , type : " + type);
        if (!wifiManager.isWifiEnabled()) {
            return false;
        }
        //开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右)，所以要等到wifi
        //状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
        while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
            try {
                //为了避免程序一直while循环，让它睡个100毫秒在检测……
                Thread.currentThread();
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
        }
        WifiConfiguration wifiConfig = CreateWifiInfo(SSID, password, type);
        if (wifiConfig == null) {
            return false;
        }

        WifiConfiguration tempConfig = isExist(wifiManager, SSID);
        if (tempConfig != null) {
            wifiManager.removeNetwork(tempConfig.networkId);
        }

//        wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
//        wifiManager.disconnect();

        int netID = wifiManager.addNetwork(wifiConfig);
        boolean bRet = wifiManager.enableNetwork(netID, true);
        return bRet;
    }

    //查看以前是否也配置过这个网络
    public static WifiConfiguration isExist(WifiManager wifiManager, String SSID) {
        List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
        if (existingConfigs == null) {
            return null;
        }

        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig != null && SSID.equals(existingConfig.SSID)) {
                return existingConfig;
            }
        }
        return null;
    }

    public static class WifiCipherType {
        public static final int WIFICIPHER_WEP = 0;
        public static final int WIFICIPHER_WPA = 1;
        public static final int WIFICIPHER_NOPASS = 2;
        public static final int WIFICIPHER_INVALID = 3;

        private int groupCipher;
        private int keyMgmt;
        private int protocol;
        private int pairwiseCiphers;
        private String capabilities;
        private int connectType;

        public WifiCipherType(String capabilities) {
            this.capabilities = capabilities;
            resolve();
        }

        public int getGroupCipher() {
            return groupCipher;
        }

        public int getKeyMgmt() {
            return keyMgmt;
        }

        public int getProtocol() {
            return protocol;
        }

        public int getPairwiseCiphers() {
            return pairwiseCiphers;
        }

        public void resolve() {
            if (capabilities.equals("")) {
                return;
            }
            String tmp1 = capabilities.split("]")[0];
            String tmp2;
            if (tmp1.contains("[")) {
                tmp2 = tmp1.substring(1, tmp1.length());
            } else {
                tmp2 = tmp1;
            }

            String[] str = tmp2.split("-");

            for (int i = 0; i < str.length; i++) {
                System.out.println(str[i]);
            }
            if (str.length >= 3) {
                if (str[2].contains("WEP40")) {
                    groupCipher = WifiConfiguration.GroupCipher.WEP40;
                } else if (str[2].contains("WEP104")) {
                    groupCipher = WifiConfiguration.GroupCipher.WEP104;
                } else if (str[2].contains("TKIP")) {
                    groupCipher = WifiConfiguration.GroupCipher.TKIP;
                    keyMgmt = WifiConfiguration.PairwiseCipher.TKIP;
                } else if (str[2].contains("CCMP")) {
                    groupCipher = WifiConfiguration.GroupCipher.CCMP;
                    keyMgmt = WifiConfiguration.PairwiseCipher.CCMP;
                } else if (str[2].contains("NONE")) {
                    keyMgmt = WifiConfiguration.PairwiseCipher.NONE;
                }
            }

            if (str.length >= 2) {
                if (str[1].contains("PSK")) {
                    keyMgmt = WifiConfiguration.KeyMgmt.WPA_PSK;
                } else if (str[1].contains("EAP")) {
                    keyMgmt = WifiConfiguration.KeyMgmt.WPA_EAP;
                } else if (str[1].contains("IEEE8021X")) {
                    keyMgmt = WifiConfiguration.KeyMgmt.IEEE8021X;
                } else {
                    keyMgmt = WifiConfiguration.KeyMgmt.NONE;
                }
            }

            if (str.length >= 1) {
                if (str[0].contains("RSN")) {
                    keyMgmt = WifiConfiguration.Protocol.RSN;
                    connectType = WIFICIPHER_WPA;
                } else {
                    keyMgmt = WifiConfiguration.Protocol.WPA;
                    connectType = WIFICIPHER_WPA;
                }
            }
        }

        public int getType() {
            return connectType;
        }
    }
}
